package cn.engage.org.service.impl;

import cn.engage.basic.config.BussinessException;
import cn.engage.basic.service.impl.BaseServiceImpl;
import cn.engage.org.domain.Employee;
import cn.engage.org.domain.Shop;
import cn.engage.org.mapper.EmployeeMapper;
import cn.engage.org.mapper.ShopMapper;
import cn.engage.org.service.ShopService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /*店铺入驻*/
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = getEmployee(shop, admin);

        shopMapper.add(shop);
        if (null == employee){
            employee = admin;
            employeeMapper.add(employee);
        }
        employee.setShopId(shop.getId());
        employeeMapper.update(employee);
        Shop uptShop = new Shop();
        uptShop.setId(shop.getId());
        uptShop.setAdminId(employee.getId());
        shopMapper.update(uptShop);
    }

    private Employee getEmployee(Shop shop, Employee admin) {
        // 店铺名字不能为空
        if (StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名字不能为空");
        }
        // 验证密码
        if (StringUtils.isBlank(admin.getPassword())){
            throw new BussinessException("请输入密码");
        }else {
            if (!admin.getPassword().equals(admin.getComfirmPassword())){
                throw new BussinessException("两次输入的密码不一致");
            }
        }
        // AI验证

        // 验证店铺是否已经存在
        Shop shopByName = shopMapper.findByName(shop.getName());
        if (null != shopByName){
            throw new BussinessException("店铺已经存在");
        }
        // 验证当前注册人是否已经管理了店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (employee != null && employee.getShopId() != null){
            if (employee.getShopId().equals(shop.getId())){
                throw new BussinessException("当前用户已管理了店铺");
            }
        }
        return employee;
    }

}
